using model.entity;
using UnityEngine;

public class BulletController : MonoBehaviour
{
    private BulletData data;
    private Vector2 direction;
    private int penetrationCount;
    
    public void Initialize(BulletData bulletData, Vector2 fireDirection)
    {
        data = bulletData;
        direction = fireDirection;
        penetrationCount = data.penetration;
        
        // 设置子弹大小
        transform.localScale = new Vector3(data.size, data.size, 1f);
        
        // 如果子弹有爆炸效果，设置生命周期
        if (data.explosionRadius > 0)
        {
            Destroy(gameObject, 5f); // 5秒后自动销毁
        }
    }
    
    private void Update()
    {
        // 移动子弹
        transform.Translate(direction * data.speed * Time.deltaTime);
    }
    
    private void OnTriggerEnter2D(Collider2D other)
    {
        // 忽略玩家和子弹之间的碰撞
        if (other.CompareTag("Player") || other.CompareTag("Bullet"))
            return;
        
        // 处理伤害
        IDamageable damageable = other.GetComponent<IDamageable>();
        if (damageable != null)
        {
            damageable.TakeDamage(data.damage);
        }
        
        // 爆炸子弹处理
        if (data.explosionRadius > 0)
        {
            Explode();
            Destroy(gameObject);
            return;
        }
        
        // 穿透处理
        if (penetrationCount > 0)
        {
            penetrationCount--;
        }
        else
        {
            // 创建击中效果
            if (data.hitEffectPrefab != null)
            {
                Instantiate(data.hitEffectPrefab, transform.position, Quaternion.identity);
            }
            Destroy(gameObject);
        }
    }
    
    private void Explode()
    {
        // 创建爆炸效果
        if (data.hitEffectPrefab != null)
        {
            Instantiate(data.hitEffectPrefab, transform.position, Quaternion.identity);
        }
        
        // 爆炸伤害
        Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, data.explosionRadius);
        foreach (Collider2D collider in colliders)
        {
            IDamageable damageable = collider.GetComponent<IDamageable>();
            if (damageable != null)
            {
                // 根据距离减少伤害
                float distance = Vector2.Distance(transform.position, collider.transform.position);
                float damageMultiplier = 1 - Mathf.Clamp01(distance / data.explosionRadius);
                damageable.TakeDamage(data.damage * damageMultiplier);
            }
        }
    }
}

public interface IDamageable
{
    void TakeDamage(float damage);
}